/**
 * Copyright © 2013 Creativor Studio.
 * About license information, please see LICENSE.txt.
 */
package org.creativor.rayson.share.transport.http;

import org.creativor.rayson.share.annotation.NotNull;

/**
 * {@link HttpHeaders} with extended function that can parse out content length.
 * 
 * @author creativor
 */
final public class ExtendedHttpHeaders extends HttpHeaders {
	private AbstractHttpMessage message;

	private boolean foundContentLength;

	public ExtendedHttpHeaders() {
		super();
	}

	@Override
	public void add(@NotNull final HttpHeader header)
			throws HttpProtocolException {
		if (!foundContentLength) {
			foundContentLength = header.getName().equals(
					HttpConstants.CONTENT_LENGTH_HEADER_NAME);
			if (foundContentLength) {
				try {
					final int bodyLength = Integer.valueOf(header.getValue());
					this.message.setBodyLength(bodyLength);
				} catch (final Exception e) {
					throw new HttpProtocolException("Header " + header
							+ " is wrong format");
				}
			}
		}
		super.add(header);
	}

	/**
	 * @param message
	 *            the message to set
	 */
	public void setMessage(@NotNull final AbstractHttpMessage message) {
		this.message = message;
	}
}
